import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
// 引入userStore
import { useUserStore } from '@/store/modules/user'
// 引入router实例
import router from '@/router'

//创建axios实例
let request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})
//请求拦截器
request.interceptors.request.use((config) => {
  // 1.从pinia中获取token数据
  const userStore = useUserStore()
  // 2.按照后端的要求拼接token
  const token = userStore.userInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
//响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const userStore = useUserStore()
    ElMessage({
      type: 'warning',
      message: error.response.data.msg,
    })
    // 401 token失效处理
    // 1.清除本地用户数据
    // 2.跳转到登录页
    if (error.response.status === 401) {
      userStore.clearUserInfo()
      router.push('/login')
    }
    return Promise.reject(error)
  },
)
export default request
